﻿using UnityEngine;

public class GridManager {
	// === Public =====================================================================================================
	public static GridManager CreateInstance() {
		var instance = new GridManager();
		return instance;
	}

	public void Create(GameObject parent) {
		_fieldSize = SettingsLevelModel.FieldSize;
		CreateGo(parent);
	}

	public void Destroy() {
		if (_go == null) {
			return;
		}
		Object.Destroy(_go);
		_go = null;
	}

	// === Private ====================================================================================================
	private Vector2 _fieldSize;
	private GameObject _go;

	private void CreateGo(GameObject parent) {
		_go = Tools.Prefab.Create<GameObject>(Constants.Resources.Prefabs.GameBoard.GRID, GetPosition(), GetQuaternion());
		_go.transform.parent = parent.transform;
		_go.transform.localScale = GetScale();
		_go.renderer.material.mainTextureScale = _fieldSize;
	}

	private Vector3 GetPosition() {
		var centerPointX = Constants.CELL_LENGTH * _fieldSize.x * .5f - Constants.CELL_LENGTH_HALF;
		var centerPointY = Constants.CELL_LENGTH * _fieldSize.y * .5f - Constants.CELL_LENGTH_HALF;
		return new Vector3(centerPointX, -0.4f, centerPointY);
	}

	private Quaternion GetQuaternion() {
		return Quaternion.Euler(90, 0, 0);
	}

	private Vector3 GetScale() {
		var localScaleX = Constants.CELL_LENGTH * _fieldSize.x;
		var localScaleY = Constants.CELL_LENGTH * _fieldSize.y;
		return new Vector3(localScaleX, localScaleY, 1);
	}
}